package com.dtx.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.dtx.dao.FileDao;
import com.dtx.entity.SysFile;
import com.dtx.service.IFileService;
import com.dtx.utils.HttpContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class FileServiceImpl implements IFileService {

    @Autowired
    private FileDao fileDao;

    @Override
    public void insert(SysFile sysFile) {
        fileDao.insert(sysFile);
    }

    @Override
    public String upload(InputStream inputStream,String name) throws IOException {
        name = name.replaceAll(",","");
        String suff = name.substring(name.lastIndexOf("."));
        name = UUID.randomUUID().toString()+suff;
        String ymkDirectory = DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN);
        HttpServletRequest request = HttpContext.getRequest();
        String realPath = request.getSession().getServletContext().getRealPath("/");
        System.out.println("==========================================================="+realPath);
        realPath = (new File(realPath)).getParent();
        log.info("-----------------------------" + realPath);
        String fileDirectoryAddress =realPath+"/upload/"+ymkDirectory;
        mkdirs(fileDirectoryAddress);
        // 保存文件地址
        File newFile = new File(fileDirectoryAddress + "/" + name);
        FileUtil.writeFromStream(inputStream, newFile);
        IoUtil.close(inputStream);
        String absolutePath = newFile.getAbsolutePath();
        System.out.println(absolutePath);
        log.info(absolutePath);
        return "/upload/"+ymkDirectory + "/" + name;
    }
}
